package com.lnlyj.media.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.lnlyj.media.Config;
import com.lnlyj.media.R;
import com.lnlyj.media.base.BaseFragment;
import com.lnlyj.media.data.MediaItem;
import com.lnlyj.media.data.load.QueryConfig;
import com.lnlyj.media.widget.GalleryRecyclerView;
import com.lnlyj.media.widget.MediaToolBar;

import java.util.List;

import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static com.lnlyj.media.Constants.EXTRA_CONFIG;
import static com.lnlyj.media.Constants.EXTRA_PREVIEW_POSITION;
import static com.lnlyj.media.Constants.EXTRA_QUERY_CONFIG;
import static com.lnlyj.media.Constants.EXTRA_RESULT_DATA;

/**
 * wanglei 2020-04-20
 */
public class AlbumFragment extends BaseFragment {

    public static final String TAG = "AlbumFragment";

    private MediaToolBar toolBar;
    private ViewPager2 mediaPager;
    private GalleryRecyclerView recyclerView;
    private View optionView;
    private TextView selectTv;
    private TextView fullImageTv;

    private AlbumMediaAdapter albumMediaAdapter;
    private PreviewAdapter previewAdapter;

    private MediaViewModel viewModel;

    private QueryConfig queryConfig;
    private Config config;
    private int position;

    private boolean showOption = true;


    private ViewPager2.OnPageChangeCallback pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            MediaItem item = albumMediaAdapter.getItem(position);
            if (previewAdapter != null) {
                previewAdapter.setCurrentItem(item);

                setupPreviewPosition(item);

            }

            selectTv.setSelected(SelectionManager.getInstance().contains(item));
            toolBar.setTitle(String.format("%d/%d", mediaPager.getCurrentItem() + 1, albumMediaAdapter.getItemCount()));
        }
    };

    public static AlbumFragment getInstance(QueryConfig queryConfig, Config config, int position) {
        AlbumFragment fragment = new AlbumFragment(R.layout.fragment_album);

        Bundle bundle = new Bundle();

        if (queryConfig != null) {
            bundle.putParcelable(EXTRA_QUERY_CONFIG, queryConfig);
        }
        bundle.putParcelable(EXTRA_CONFIG, config);
        bundle.putInt(EXTRA_PREVIEW_POSITION, position);

        fragment.setArguments(bundle);

        return fragment;
    }

    public AlbumFragment(int layoutId) {
        super(layoutId, false);
    }

    public AlbumFragment() {
        super();
    }

    @Override
    public void initBundleData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            queryConfig = bundle.getParcelable(EXTRA_QUERY_CONFIG);
            config = bundle.getParcelable(EXTRA_CONFIG);
            position = bundle.getInt(EXTRA_PREVIEW_POSITION);
        }
    }

    @Override
    protected void initViewModel() {
        viewModel = ViewModelProviders.of(this).get(MediaViewModel.class);

        viewModel.getMediaLiveData().observe(this, list->{
            setupMediaAdapter(list.get(0).items);
            toolBar.setTitle(String.format("%d/%d", position + 1, list.get(0).items.size()));
        });
    }

    @Override
    public void initView() {
        toolBar = findViewById(R.id.toolbar);
        mediaPager = findViewById(R.id.pager_media);
        recyclerView = findViewById(R.id.recycler_view);
        optionView = findViewById(R.id.layout_option);
        selectTv = findViewById(R.id.tv_select);
        fullImageTv = findViewById(R.id.tv_full_image);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        recyclerView.setAdapter(previewAdapter = new PreviewAdapter(queryConfig == null));

        mediaPager.setOffscreenPageLimit(2);
        mediaPager.registerOnPageChangeCallback(pageChangeCallback);

        toolBar.setCloseListener(()-> {
            setResult(RESULT_CANCELED);
        });

        toolBar.setSelectorListener(()-> {
            SelectionManager manager = SelectionManager.getInstance();
            if (manager.getSize() > 0) {
                Intent data = new Intent();
                data.putExtra(EXTRA_RESULT_DATA, manager.getResultData());
                setResult(RESULT_OK, data);
            } else {
                manager.add(albumMediaAdapter.getItem(mediaPager.getCurrentItem()));
                Intent data = new Intent();
                data.putExtra(EXTRA_RESULT_DATA, manager.getResultData());
                setResult(RESULT_OK, data);
            }
        });

        previewAdapter.setOnItemClickListener((item, position) -> {
            int index = albumMediaAdapter.getIndex(item);
            if (index >= 0) {
                mediaPager.setCurrentItem(index, false);
            }
        });

        selectTv.setOnClickListener(view -> {
            MediaItem item = albumMediaAdapter.getItem(mediaPager.getCurrentItem());
            SelectionManager manager = SelectionManager.getInstance();

            if (manager.getSize() < config.getSelectCount()) {
                manager.toggle(item);
            } else {
                if (manager.contains(item)) {
                    manager.remove(item);
                } else {
                    snackMsg(getString(R.string.toast_max_select, config.getSelectCount()));
                }
            }

            previewAdapter.notifyDataSetChanged();
            selectTv.setSelected(manager.contains(item));
            checkPreview();
        });

        fullImageTv.setOnClickListener(view -> {
            fullImageTv.setSelected(!fullImageTv.isSelected());
            SelectionManager.getInstance().setFullImage(fullImageTv.isSelected());
        });
    }

    @Override
    public void initData() {

        if (queryConfig != null) {
            viewModel.getMediaData(queryConfig);
        } else {
            setupMediaAdapter(SelectionManager.getInstance().getMediaItems());
        }

        previewAdapter.swapResult(SelectionManager.getInstance().getMediaItems());

        fullImageTv.setSelected(SelectionManager.getInstance().isFullImage());
        checkPreview();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPager.unregisterOnPageChangeCallback(pageChangeCallback);
    }

    private void setupMediaAdapter(List<MediaItem> list) {
        albumMediaAdapter = new AlbumMediaAdapter();
        albumMediaAdapter.swapResult(list);
        albumMediaAdapter.setOnItemClickListener((item, position) -> {
            toggleOption();
        });
        mediaPager.setAdapter(albumMediaAdapter);
        mediaPager.setCurrentItem(position, false);
        toolBar.setTitle(String.format("%d/%d", position, list.size()));

        setupPreviewPosition(albumMediaAdapter.getItem(position));
    }

    private void checkPreview() {

        int selectSize = SelectionManager.getInstance().getSize();

        if (selectSize > 0) {
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.GONE);
        }

        String sendText;

        if (selectSize > 0) {
            sendText = String.format(getString(R.string.media_text_send) + "(%d/%s)", selectSize, config.getSelectCount());
        } else {
            sendText = getString(R.string.media_text_send);
        }

        toolBar.setSendButtonText(sendText);
    }

    private void setupPreviewPosition(MediaItem item) {

        recyclerView.post(()->{
            int index = previewAdapter.getList().indexOf(item);
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

            int firstPosition = layoutManager.findFirstVisibleItemPosition();
            int lastPosition = layoutManager.findLastVisibleItemPosition();

            if (index <= firstPosition || index >= lastPosition) {
                recyclerView.scrollToPosition(index);
            }
        });
    }


    private void toggleOption() {

        showOption = !showOption;

        if (showOption) {
            toolBar.setVisibility(View.VISIBLE);
            optionView.setVisibility(View.VISIBLE);
            if (SelectionManager.getInstance().getSize() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
            }
        } else {
            toolBar.setVisibility(View.GONE);
            optionView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        }
    }

}
